package cn.com.tom.util;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.FileUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class Uploads {

    private static String DIR = "upload/img";

    /**
     * 上传图片
     *
     * @param item    文件item
     * @param request 请求
     * @return 图片路径
     * @throws Exception
     */
    public static String uploadImage(FileItem item, HttpServletRequest request) throws Exception {
        if (item == null || item.getInputStream() == null || item.getInputStream().available() == 0) return null;

        String dir = request.getServletContext().getRealPath(DIR);
        String extension = "";
        int index = item.getName().lastIndexOf(".");
        if (index != -1) {
            extension = item.getName().substring(index + 1);
        }
        String fileName = UUID.randomUUID() + "." + extension;
        FileUtils.copyInputStreamToFile(item.getInputStream(), new File(dir, fileName));
        return "/upload/img/" + fileName;
    }


}
